<template>
  <el-tree class="x-select-tree" ref="platform" highlight-current node-key="value" @check="handleCheckChange" :default-checked-keys="viewModel" :accordion="true" :data="treeData" show-checkbox :props="props" v-if="treeData" empty-text="暂无数据"></el-tree>
</template>

<script>
  import api from 'api'
  import ala from 'ala'
  export default {
    model: {
      prop: 'dataModel',
      event: 'change'
    },
    props: {
      type: {},
      label: {
        default: ''
      },
      size: {},
      dataModel: {}
    },
    data () {
      return {
        props: {
          children: 'children',
          label: 'label'
        },
        treeData: null,
        viewModel: []
      }
    },
    mounted () {
      this.init()
    },
    methods: {
      async init () {
        this.treeData = await api.relationTree(this.type)
        if (!this.treeData) {
          this.$ala.error('类型输入错误')
        }
        if (this.dataModel) {
          this.viewModel = this.dataModel
        }
        if (!this.viewModel) {
          this.viewModel = []
        }
        this.$forceUpdate()
      },
      handleCheckChange () {
        this.$nextTick(() => {
          if (this.$refs.platform) {
            this.viewModel = this.$refs.platform.getCheckedKeys()
          }
        })
      }
    },
    watch: {
      viewModel: {
        deep: true,
        handler (val) {
          this.$emit('change', this.viewModel)
        }
      }
    }
  }
</script>


<style lang="scss" scoped>
  .x-select-tree {
    border: 1px solid #ebedf2;
    border-radius: 5px;
    width: 100%;
    max-height: 280px;
    min-height: 150px;
    overflow-y: scroll;
  }
</style>


